/**
 * MouseHandeling.java
 * Auti i class hirizete ola ta Events tou mouse pano ston Board kai andidra analoga.
 */

package GUI;

import java.awt.event.*;
 
public class MouseHandeling extends MouseAdapter{
    static int clickCounter;
    static String pieceName;
    static SquareOnBoard FromOriginal;
    static SquareOnBoard ToThis;
    
    /**
     * Kani set-constract/reset tin metaclites tis MouseHandeling
     */
    public MouseHandeling(){ reset(); }
 
    @Override
    public void mouseClicked(MouseEvent e){
        if(e.getSource() instanceof SquareOnBoard){ boardHandeler(e); }
        else if(e.getSource() instanceof sqrGUI){ pieceHandeler(e); }
    }
    
    /**
     * Vazi to Piece stin thesi pou epilegi to mouce sto ChessBoard.
     * @param boardEvent To event tou mouse sto ChessBoard.
     */
    private void boardHandeler(MouseEvent boardEvent){
        if((pieceName != null) && (clickCounter == 1)){
            ToThis = (SquareOnBoard)boardEvent.getComponent();
            FromOriginal.removePiece();
            ToThis.removePiece();
            sqrGUI p = new sqrGUI(pieceName,true);
            p.addMouseListener(this);
            ToThis.addPiece(p);
            reset();
        }
    }
    
    /**
     * Kani set-reset tis metavlites.
     */
    private void reset(){
        clickCounter = 0;
        ToThis = null;
        FromOriginal = null;
        pieceName = null;  
    }
    
    
    private void pieceHandeler(MouseEvent pieceEvent){ 
        /*
         * An o pektis prospathouse na kinisi ena Piece ala meta epelege ena alo sto telos to proto tha metakinoundan stin thesi. Auto apotrepete apo tin reset().
         */
        reset();
        sqrGUI temp = (sqrGUI)pieceEvent.getComponent();
        if((pieceName == null) && temp.getIfMovable() && (clickCounter == 0)){
            pieceName= temp.getName();
            FromOriginal = (SquareOnBoard)temp.getParent();
            clickCounter++; // kani to clickCounter=1.
        }
    }
}